﻿using AutoMapper;
using MediatR;
using Traceability.App.API.Application.Command.Img;
using Traceability.App.Domain.Entities;
using Traceability.App.ErrorCode;
using Traceability.App.Infrastructure.Interface;

namespace Traceability.App.API.Application.Handler.Img
{
    /// <summary>
    /// 图片上传请求命令处理类
    /// </summary>
    public class CreateImgHandler:IRequestHandler<CreateImgCommand,ApiResult<int>>
    {
        IBaseRepository<Picture_Information> pictureRep;
        IMapper mapper;

        public CreateImgHandler(IBaseRepository<Picture_Information> pictureRep, IMapper mapper)
        {
            this.pictureRep = pictureRep;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(CreateImgCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> res = new ApiResult<int>();
                var model = mapper.Map<Picture_Information>(request);
                int r = pictureRep.CreateAsync(model).Result;
                if (r > 0)
                {
                    res.Msg = "图片保存成功";
                    res.Code = ApiEnum.Success;
                    res.Data = r;
                }
                else
                {
                    res.Msg = "图片保存失败";
                    res.Code = ApiEnum.Fail;
                }
                return Task.FromResult(res);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
